﻿
    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;

namespace ConsoleRSA
{
    public class Program
    {
        //openssl genrsa -out rsa_1024_priv.pem 1024
        private static readonly string _privateKey = @"lF7SnRYDN05MSQSpL+w7pt82H6u3yuiepmDXZBDxDQ8ujStEa+6FZKI2exv9O13P
GysNBRZHAuJty9L/5oxWe4O+Ye7EveulnCR/6aVH9VQOpgnzJyhPCPrYZsCFKApr
7ikXiPZ0P55ABRpGfa3WIPRxuUU+QZlBoAdyAYm0CsMk5mTzhtzkFrGReE6nT/mL
HgNPGwCxJgXVD4GDBJYghhQ1Wrk8BL2s/02BehV41Tl4tWOeMglS9TEAp/RIsnQY
QmOie26HE/PnB4sznAndtikFwR0G0lco6hSpv5UHvZGWB9wxNMjWij+03fG+8z45
qAg1S4tRbdss/lGU+UgCDHjH+5XyTFFy6u4Ss71cfMnVWaDs4R100fLjTX0BVtE4
SmkZehKHlLZt5cbdH+TKGYr0wBAIYHAVGaYlm61uxtXr42xNVzQYLCEhns/3TKS2
MLoo24FlwBLO13wJnsRnXhVfuApTrtCzTFxGYMfw2vzLZw4BLPZMF6uulTuta7up
a0ScVqxQ3BrPJ7y2kyEOhwd9BOG5B0XPPFY8a/SVVj3UPlwD4xNOTnEbWL3mSzxg
aew27ExlgbPk3ojos7J5HKvaU6y3lDRqdW9dU/jUXc9Lr3BZqzw0dnly4Vtv71L+
7A1c5JqWheC9isj7Lg5olkOKkRRv6DgZDIPUan1bmTsZpjBAorX3Wy6iCJ9nCDWI
GnHPfY+AVw97Co6wNUJc7gQyCr0kcLFsR/yuPuwQEArdaUEeMI+Czyo+6FC4lsvX
KxoScdzKv8+3PDmdWVP4sxRETIIUNUEM7cGnjgV5hTIgzz17HLajPE5qNZfAAmW9
bGHQwdCfriHk1YaXnf+M5uka0EeSf/FIueTXStE2+KKYRJNraWMCCJnGhPGz+maN
rncVsrDVlbgDb10wTjnRbzSU5ctIBlj5Ds40NgD3RRlxWP3SbasmPHcM/eD/Un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zZ8KZACggjiNUVrSFV3Y4oWom93K5JLXf2mV0Sy
80mPR5jOdwJBAMwciAk8xyQKpMUGNhFX2jKboAYY1SJCfuUnyXHAPWeHp5xCL2UH
tjryJp/Vx8TgsFTGyWSyIE9R8hSup+32rkcCQBe+EAkC7yQ0np4Z5cql+sfarMMm
4+Z9t8b4N0a+EuyLTyfs5Dtt5JkzkggTeuFRyOoALPJP0K6M3CyMBHwb7WsCQQCi
TM2fCsUO06fRQu8bO1A1janhLz3K0DU24jw8RzCMckHE7pvhKhCtLn+n+MWwtzl/
L9JUT4+BgxeLepXtkolhAkEA2V7er7fnEuL0+kKIjmOm5F3kvMIDh9YC1JwLGSvu
1fnzxK34QwSdxgQRF1dfIKJw73lClQpHZfQxL/2XRG8IoA==".Replace("\n", "");
        */

        //openssl rsa -pubout -in rsa_1024_priv.pem -out rsa_1024_pub.pem
        private static readonly string _publicKey = @"MIGJAoGBAKvFwEsQJRf/gTv2H9YGOw2LFs45xnToRcEIlJDn7AGrh6Lv8hbRfxGwo3Np2Af7o1wLd2pxeFNe6Y7tBOtuEx4pUH89CDNkrbT8OBRfRFzc3tDGeenXotz1V9G9v7Th1EDwvvpVoOphigz9EmyilWd+DL8uAiykU53uGedNFmTTAgMBAAE=".Replace("\n", "");
         
                                                /** @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0xP5HcfThSQr43bAMoopbzcCyZWE0xfUeTA4Nx4PrXEfDvybJEIjbU/rgANAty1yp7g20J7+wVMPCusxftl/d0rPQiCLjeZ3HtlRKld+9htAZtHFZosV29h/hNE9JkxzGXstaSeXIUIWquMZQ8XyscIHhqoOmjXaCv58CSRAlAQIDAQAB".Replace("\n", "");
            */

        public static void Main(string[] args)
        {
            var plainText = "cnblogs.com";

            //Encrypt
            RSA rsa = CreateRsaFromPublicKey(_publicKey);
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            var cipherBytes = rsa.Encrypt(plainTextBytes, RSAEncryptionPadding.Pkcs1);
            var cipher = Convert.ToBase64String(cipherBytes);
            Console.WriteLine($"{nameof(cipher)}:{cipher}");

            //Decrypt
            rsa = CreateRsaFromPrivateKey(_privateKey);
            cipherBytes = System.Convert.FromBase64String(cipher);
            plainTextBytes = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.Pkcs1);
            plainText = Encoding.UTF8.GetString(plainTextBytes);
            Console.WriteLine($"{nameof(plainText)}:{plainText}");
        }
        private static RSA CreateRsaFromPrivateKey(string privateKey)
        {
            var privateKeyBits = System.Convert.FromBase64String(privateKey);
            var rsa = RSA.Create();
            var RSAparams = new RSAParameters();

            using (var binr = new BinaryReader(new MemoryStream(privateKeyBits)))
            {
                byte bt = 0;
                ushort twobytes = 0;
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130)
                    binr.ReadByte();
                else if (twobytes == 0x8230)
                    binr.ReadInt16();
                else
                    throw new Exception("Unexpected value read binr.ReadUInt16()");

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102)
                    throw new Exception("Unexpected version");

                bt = binr.ReadByte();
                if (bt != 0x00)
                    throw new Exception("Unexpected value read binr.ReadByte()");

                RSAparams.Modulus = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.Exponent = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.D = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.P = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.Q = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.DP = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.DQ = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
            }

            rsa.ImportParameters(RSAparams);
            return rsa;
        }

        private static int GetIntegerSize(BinaryReader binr)
        {
            byte bt = 0;
            byte lowbyte = 0x00;
            byte highbyte = 0x00;
            int count = 0;
            bt = binr.ReadByte();
            if (bt != 0x02)
                return 0;
            bt = binr.ReadByte();

            if (bt == 0x81)
                count = binr.ReadByte();
            else
                if (bt == 0x82)
            {
                highbyte = binr.ReadByte();
                lowbyte = binr.ReadByte();
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                count = BitConverter.ToInt32(modint, 0);
            }
            else
            {
                count = bt;
            }

            while (binr.ReadByte() == 0x00)
            {
                count -= 1;
            }
            binr.BaseStream.Seek(-1, SeekOrigin.Current);
            return count;
        }

        private static RSA CreateRsaFromPublicKey(string publicKeyString)
        {
            byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] x509key;
            byte[] seq = new byte[15];
            int x509size;

            x509key = Convert.FromBase64String(publicKeyString);
            x509size = x509key.Length;

            using (var mem = new MemoryStream(x509key))
            {
                using (var binr = new BinaryReader(mem))
                {
                    byte bt = 0;
                    ushort twobytes = 0;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130)
                        binr.ReadByte();
                    else if (twobytes == 0x8230)
                        binr.ReadInt16();
                    else
                        return null;

                    seq = binr.ReadBytes(15);
                    if (!CompareBytearrays(seq, SeqOID))
                        return null;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8103)
                        binr.ReadByte();
                    else if (twobytes == 0x8203)
                        binr.ReadInt16();
                    else
                        return null;

                    bt = binr.ReadByte();
                    if (bt != 0x00)
                        return null;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130)
                        binr.ReadByte();
                    else if (twobytes == 0x8230)
                        binr.ReadInt16();
                    else
                        return null;

                    twobytes = binr.ReadUInt16();
                    byte lowbyte = 0x00;
                    byte highbyte = 0x00;

                    if (twobytes == 0x8102)
                        lowbyte = binr.ReadByte();
                    else if (twobytes == 0x8202)
                    {
                        highbyte = binr.ReadByte();
                        lowbyte = binr.ReadByte();
                    }
                    else
                        return null;
                    byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                    int modsize = BitConverter.ToInt32(modint, 0);

                    int firstbyte = binr.PeekChar();
                    if (firstbyte == 0x00)
                    {
                        binr.ReadByte();
                        modsize -= 1;
                    }

                    byte[] modulus = binr.ReadBytes(modsize);

                    if (binr.ReadByte() != 0x02)
                        return null;
                    int expbytes = (int)binr.ReadByte();
                    byte[] exponent = binr.ReadBytes(expbytes);

                    var rsa = RSA.Create();
                    var rsaKeyInfo = new RSAParameters
                    {
                        Modulus = modulus,
                        Exponent = exponent
                    };
                    rsa.ImportParameters(rsaKeyInfo);
                    return rsa;
                }

            }
        }

        private static bool CompareBytearrays(byte[] a, byte[] b)
        {
            if (a.Length != b.Length)
                return false;
            int i = 0;
            foreach (byte c in a)
            {
                if (c != b[i])
                    return false;
                i++;
            }
            return true;
        }
    }
}

